package com.lanhai.system;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lanhai.Main;
import com.lanhai.utils.PropsUtil;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;





public class LoginHandler implements HttpHandler {
	
	public Main main;
	
    @Override
    public void handle(HttpExchange httpExchange) {
    	try{
            InputStream is = httpExchange.getRequestBody();
            
            String requestData = is2string(is);
            System.out.println(requestData); 
            String queryParams = httpExchange.getRequestURI().getQuery();
            System.out.println(queryParams);
            String response = "";
            
            Map<String, Object> map = new HashMap<String, Object>();
            
    		String spassword = PropsUtil.getString(Main.props, "spassword");
            JSONObject object = JSONObject.parseObject(new String(requestData));
            String pwd = object.getString("pwd");
    		if(spassword.equals(pwd)){
    			map.put("success", true);
    		}else{
    			map.put("success", false);
    		}
            response = JSON.toJSONString(map);
            System.out.println("response: " + response);        
            is.close();
            
            Headers responseHeaders = httpExchange.getResponseHeaders();
            responseHeaders.set("Content-Type", "text/json;charset=utf-8");
            httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.getBytes().length); 
            OutputStream os = httpExchange.getResponseBody();
            os.write(response.getBytes());
            os.flush();
            os.close();      		
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
	
    public void init(Main main){
    	this.main = main;
    }
    
    private String is2string(InputStream is) throws IOException {
        final int bufferSize = 1024;
        final char[] buffer = new char[bufferSize];
        final StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(is, "UTF-8");
        
        for (; ; ) {
            int rsz = in.read(buffer, 0, buffer.length);
            if (rsz < 0)
                break;
            out.append(buffer, 0, rsz);
        }
        return out.toString();
    }
    
}
